﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Company;
using B.S.Traceability.Writer.API.Application.Commends.Processs;
using MediatR;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Processs
{
    /*public class CreateProcessCommendHandlers:IRequestHandler<CreateProcessCommends,APIResult<Process>>
    {
    }
*/


    public class CreateProcessCommendHandlers : IRequestHandler<CreateProcessCommends, APIResult<Process>>
    {
        private readonly IBaseRepository<Process> companysRepository;
        private readonly IMapper mapper;

        public CreateProcessCommendHandlers(IBaseRepository<Process> companysRepository, IMapper mapper)
        {
            this.companysRepository = companysRepository;
            this.mapper = mapper;
        }







        /// <summary>
        /// 添加深加工信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Process>> Handle(CreateProcessCommends request, CancellationToken cancellationToken)
        {
            APIResult<Process> result = new APIResult<Process>();
      
            var exist =  companysRepository.GetAllAsync().Result.FirstOrDefault(x => x.BatchId == request.BatchId);
            if (exist == null)
            {
                var farm = mapper.Map<Process>(request);

                farm.BatchId = request.BatchId;
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                await companysRepository.Add(farm);
            }
            else
            {
                mapper.Map(request,exist);
              await   companysRepository.Update(exist);
                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功   ";
            }
          
            return await Task.FromResult(result);
        }
    }
}
